//
//  StartViewController.m
//  MooreDoll
//
//  Created by Joe on 2014/11/24.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "StartViewController.h"
#define REGIST 101
#define LOGIN 102

@interface StartViewController ()
@property (weak, nonatomic) UITextField *TF_ActiveField;

@end

@implementation StartViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    //重SIM卡內取得國家 並且顯示國家
    self.TF_Country.text = [TelephonyInfo getCountryCodeString];
    
    if (![self.TF_Country.text isEqualToString:@""]) {
        [[NSUserDefaults standardUserDefaults]setValue:[TelephonyInfo getCountryCodeString] forKey:@"country"];
        [[NSUserDefaults standardUserDefaults]setValue:[TelephonyInfo getCountryCodeNumber] forKey:@"code"];
    }

}

#pragma mark 文字 鍵盤 delegate
- (void) keyboardWillShow:(NSNotification *)notification
{
    [CoverKeyboard scrollView:self.SV_main textField:self.TF_ActiveField notification:notification view:self.view];
}

- (void) keyboardWillBeHidden:(NSNotification *)notification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.SV_main.contentInset = contentInsets;
    self.SV_main.scrollIndicatorInsets = contentInsets;
}

//開始編輯
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.TF_ActiveField = textField;
}

//結束編輯
- (void)textFieldDidEndEditing:(UITextField *)sender
{
    self.TF_ActiveField = nil;
}

//按下return健
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField==self.TF_account) {
        
        [self.TF_password becomeFirstResponder];
        
    }else if(textField==self.TF_password)
        
    {
        [self.TF_password resignFirstResponder];
    }
    
    return YES;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    if (self.V_ContentView == touch.view) {
        [self.view endEditing:YES];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



-(IBAction)buttonPress:(UIButton *)sender{
    if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
        
        int tag = (int)sender.tag;
        
        if (tag == LOGIN) {
            //[self performSegueWithIdentifier:@"Login_Segue" sender:nil];
            
            //登入按鈕 檢查 帳號密碼欄位長度 和 格式
            if (self.TF_account.text.length>0 && self.TF_password.text>0 && [ValidateText validatePhone:self.TF_account.text]  && [ValidateText validatePassword:self.TF_password.text]&&self.TF_Country.text.length>0)
            {
                
                //使用 userDefaults 去紀錄帳號密碼
                [[NSUserDefaults standardUserDefaults]setValue:self.TF_account.text forKey:@"account"];
                
                
                [[NSUserDefaults standardUserDefaults]setValue:self.TF_password.text forKey:@"password"];
                
                //這邊註冊了登入後的 delegate
                [XMPPSharedInstance sharedInstance].stateDelegate = self;
                
                //執行登入
                [[XMPPSharedInstance sharedInstance] loginXMPP];
            }else
            {
                [WinkAlertView _showAlertViewWithTitle:@"注意" content:@"帳號密碼格式不正確" cancelButtonTitle:@"確認" showTime:3.0f];
                
            }
            
        }else
        {
            
            RegistViewController *registVC=[self.storyboard instantiateViewControllerWithIdentifier:@"RegistViewController"];
            [self.navigationController pushViewController:registVC animated:YES];
            
        }
    }else
    {
        [WinkAlertView _showAlertViewWithTitle:@"注意" content:@"請檢查您的網路" cancelButtonTitle:@"確認" showTime:3.0f];
        
    }
}
//選擇國碼
- (IBAction)pushCountrySelectView:(id)sender {
    CountryTableViewController *countryTVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CountryTableViewController"];
    countryTVC.delegate = self;
    [self.navigationController pushViewController:countryTVC animated:YES];
}



#pragma mark CountryTableViewControllerDelegate
-(void)selectCountry:(NSDictionary *)countryDict
{
    self.TF_Country.text = countryDict[@"country"];
    
    [[NSUserDefaults standardUserDefaults]setValue:countryDict[@"country"] forKey:@"country"];
    
    [[NSUserDefaults standardUserDefaults]setValue:countryDict[@"code"] forKey:@"code"];
    
    
}

#pragma mark connectStateDelegate 連線的delegate
-(void)connectState:(int)state
{
    //因為這邊delegate 是在背景執行時觸發 但因為我們有做切換畫面 所以要回到主線程 不然會出問題
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
        switch (state) {
                
            case 0:
                NSLog(@"連線中斷");
                
                break;
            case 1:
                NSLog(@"進行連線");
                
                break;
            case 2:
                NSLog(@"連線成功");
                //檢查一下最後一個畫面是不是另一個登入畫面 如果不是 就返回 ，因為有可能使用者是重這個畫面跑去註冊頁面 最後又跑去另一個登入頁面
                if (![[self.navigationController.viewControllers lastObject]isKindOfClass:[LoginViewController class]]) {
                    //返回首頁
                    
                    
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                break;
            default:
                
                break;
        }
    });
}
- (IBAction)goBackStartViewController:(UIStoryboardSegue *)sender
{
    
}

@end
